package com.cencat.driver.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cencat.driver.entity.Vehicle;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 车辆数据访问层接口
 * 
 * @author cencat
 * @since 2024-01-01
 */
@Repository
@Mapper
public interface VehicleMapper extends BaseMapper<Vehicle> {

    /**
     * 根据车牌号查询车辆信息
     * 
     * @param plateNumber 车牌号
     * @param tenantId 租户ID
     * @return 车辆信息
     */
    @Select("SELECT * FROM vehicle WHERE plate_number = #{plateNumber} AND tenant_id = #{tenantId} AND deleted = 0")
    Vehicle selectByPlateNumber(@Param("plateNumber") String plateNumber, @Param("tenantId") Long tenantId);

    /**
     * 根据司机ID查询车辆列表
     * 
     * @param driverId 司机ID
     * @param tenantId 租户ID
     * @return 车辆列表
     */
    @Select("SELECT * FROM vehicle WHERE driver_id = #{driverId} AND tenant_id = #{tenantId} AND deleted = 0 ORDER BY create_time DESC")
    List<Vehicle> selectByDriverId(@Param("driverId") Long driverId, @Param("tenantId") Long tenantId);

    /**
     * 根据车辆状态查询车辆列表
     * 
     * @param status 车辆状态
     * @param tenantId 租户ID
     * @return 车辆列表
     */
    @Select("SELECT * FROM vehicle WHERE status = #{status} AND tenant_id = #{tenantId} AND deleted = 0 ORDER BY create_time DESC")
    List<Vehicle> selectByStatus(@Param("status") Integer status, @Param("tenantId") Long tenantId);

    /**
     * 根据车辆类型查询车辆列表
     * 
     * @param vehicleType 车辆类型
     * @param tenantId 租户ID
     * @return 车辆列表
     */
    @Select("SELECT * FROM vehicle WHERE vehicle_type = #{vehicleType} AND tenant_id = #{tenantId} AND deleted = 0 ORDER BY create_time DESC")
    List<Vehicle> selectByVehicleType(@Param("vehicleType") Integer vehicleType, @Param("tenantId") Long tenantId);

    /**
     * 查询可用车辆列表（状态为正常且未分配司机）
     * 
     * @param tenantId 租户ID
     * @return 可用车辆列表
     */
    @Select("SELECT * FROM vehicle WHERE status = 1 AND driver_id IS NULL AND tenant_id = #{tenantId} AND deleted = 0 ORDER BY create_time DESC")
    List<Vehicle> selectAvailableVehicles(@Param("tenantId") Long tenantId);

    /**
     * 分页查询车辆列表
     * 
     * @param page 分页参数
     * @param plateNumber 车牌号（模糊查询）
     * @param brand 品牌（模糊查询）
     * @param model 型号（模糊查询）
     * @param vehicleType 车辆类型
     * @param status 车辆状态
     * @param driverId 司机ID
     * @param tenantId 租户ID
     * @return 分页结果
     */
    @Select("<script>" +
            "SELECT * FROM vehicle WHERE tenant_id = #{tenantId} AND deleted = 0" +
            "<if test='plateNumber != null and plateNumber != \"\">" +
            " AND plate_number LIKE CONCAT('%', #{plateNumber}, '%')" +
            "</if>" +
            "<if test='brand != null and brand != \"\">" +
            " AND brand LIKE CONCAT('%', #{brand}, '%')" +
            "</if>" +
            "<if test='model != null and model != \"\">" +
            " AND model LIKE CONCAT('%', #{model}, '%')" +
            "</if>" +
            "<if test='vehicleType != null'>" +
            " AND vehicle_type = #{vehicleType}" +
            "</if>" +
            "<if test='status != null'>" +
            " AND status = #{status}" +
            "</if>" +
            "<if test='driverId != null'>" +
            " AND driver_id = #{driverId}" +
            "</if>" +
            " ORDER BY create_time DESC" +
            "</script>")
    IPage<Vehicle> selectPageWithConditions(Page<Vehicle> page,
                                           @Param("plateNumber") String plateNumber,
                                           @Param("brand") String brand,
                                           @Param("model") String model,
                                           @Param("vehicleType") Integer vehicleType,
                                           @Param("status") Integer status,
                                           @Param("driverId") Long driverId,
                                           @Param("tenantId") Long tenantId);

    /**
     * 统计车辆数量
     * 
     * @param tenantId 租户ID
     * @return 车辆总数
     */
    @Select("SELECT COUNT(*) FROM vehicle WHERE tenant_id = #{tenantId} AND deleted = 0")
    Long countByTenantId(@Param("tenantId") Long tenantId);

    /**
     * 根据状态统计车辆数量
     * 
     * @param status 车辆状态
     * @param tenantId 租户ID
     * @return 车辆数量
     */
    @Select("SELECT COUNT(*) FROM vehicle WHERE status = #{status} AND tenant_id = #{tenantId} AND deleted = 0")
    Long countByStatus(@Param("status") Integer status, @Param("tenantId") Long tenantId);

    /**
     * 根据车辆类型统计车辆数量
     * 
     * @param vehicleType 车辆类型
     * @param tenantId 租户ID
     * @return 车辆数量
     */
    @Select("SELECT COUNT(*) FROM vehicle WHERE vehicle_type = #{vehicleType} AND tenant_id = #{tenantId} AND deleted = 0")
    Long countByVehicleType(@Param("vehicleType") Integer vehicleType, @Param("tenantId") Long tenantId);

    /**
     * 统计司机的车辆数量
     * 
     * @param driverId 司机ID
     * @param tenantId 租户ID
     * @return 车辆数量
     */
    @Select("SELECT COUNT(*) FROM vehicle WHERE driver_id = #{driverId} AND tenant_id = #{tenantId} AND deleted = 0")
    Long countByDriverId(@Param("driverId") Long driverId, @Param("tenantId") Long tenantId);

    /**
     * 更新车辆状态
     * 
     * @param id 车辆ID
     * @param status 车辆状态
     * @param tenantId 租户ID
     * @return 更新行数
     */
    @Update("UPDATE vehicle SET status = #{status}, update_time = NOW() WHERE id = #{id} AND tenant_id = #{tenantId}")
    int updateStatus(@Param("id") Long id, @Param("status") Integer status, @Param("tenantId") Long tenantId);

    /**
     * 分配车辆给司机
     * 
     * @param id 车辆ID
     * @param driverId 司机ID
     * @param tenantId 租户ID
     * @return 更新行数
     */
    @Update("UPDATE vehicle SET driver_id = #{driverId}, update_time = NOW() WHERE id = #{id} AND tenant_id = #{tenantId}")
    int assignToDriver(@Param("id") Long id, @Param("driverId") Long driverId, @Param("tenantId") Long tenantId);

    /**
     * 取消车辆分配
     * 
     * @param id 车辆ID
     * @param tenantId 租户ID
     * @return 更新行数
     */
    @Update("UPDATE vehicle SET driver_id = NULL, update_time = NOW() WHERE id = #{id} AND tenant_id = #{tenantId}")
    int unassignFromDriver(@Param("id") Long id, @Param("tenantId") Long tenantId);

    /**
     * 根据司机ID取消所有车辆分配
     * 
     * @param driverId 司机ID
     * @param tenantId 租户ID
     * @return 更新行数
     */
    @Update("UPDATE vehicle SET driver_id = NULL, update_time = NOW() WHERE driver_id = #{driverId} AND tenant_id = #{tenantId}")
    int unassignAllByDriverId(@Param("driverId") Long driverId, @Param("tenantId") Long tenantId);

    /**
     * 批量更新车辆状态
     * 
     * @param ids 车辆ID列表
     * @param status 车辆状态
     * @param tenantId 租户ID
     * @return 更新行数
     */
    @Update("<script>" +
            "UPDATE vehicle SET status = #{status}, update_time = NOW() WHERE tenant_id = #{tenantId} AND id IN" +
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>" +
            "#{id}" +
            "</foreach>" +
            "</script>")
    int batchUpdateStatus(@Param("ids") List<Long> ids, @Param("status") Integer status, @Param("tenantId") Long tenantId);

    /**
     * 检查车牌号是否存在
     * 
     * @param plateNumber 车牌号
     * @param excludeId 排除的车辆ID（用于更新时检查）
     * @param tenantId 租户ID
     * @return 是否存在
     */
    @Select("<script>" +
            "SELECT COUNT(*) FROM vehicle WHERE plate_number = #{plateNumber} AND tenant_id = #{tenantId} AND deleted = 0" +
            "<if test='excludeId != null'>" +
            " AND id != #{excludeId}" +
            "</if>" +
            "</script>")
    int existsByPlateNumber(@Param("plateNumber") String plateNumber, @Param("excludeId") Long excludeId, @Param("tenantId") Long tenantId);

    /**
     * 更新车辆里程数
     * 
     * @param id 车辆ID
     * @param mileage 里程数
     * @param tenantId 租户ID
     * @return 更新行数
     */
    @Update("UPDATE vehicle SET mileage = #{mileage}, update_time = NOW() WHERE id = #{id} AND tenant_id = #{tenantId}")
    int updateMileage(@Param("id") Long id, @Param("mileage") Double mileage, @Param("tenantId") Long tenantId);

    /**
     * 更新车辆保险到期时间
     * 
     * @param id 车辆ID
     * @param insuranceExpiry 保险到期时间
     * @param tenantId 租户ID
     * @return 更新行数
     */
    @Update("UPDATE vehicle SET insurance_expiry = #{insuranceExpiry}, update_time = NOW() WHERE id = #{id} AND tenant_id = #{tenantId}")
    int updateInsuranceExpiry(@Param("id") Long id, @Param("insuranceExpiry") String insuranceExpiry, @Param("tenantId") Long tenantId);

    /**
     * 查询保险即将到期的车辆（30天内）
     * 
     * @param tenantId 租户ID
     * @return 车辆列表
     */
    @Select("SELECT * FROM vehicle WHERE insurance_expiry IS NOT NULL AND " +
            "STR_TO_DATE(insurance_expiry, '%Y-%m-%d') BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY) " +
            "AND tenant_id = #{tenantId} AND deleted = 0 ORDER BY insurance_expiry ASC")
    List<Vehicle> selectInsuranceExpiringSoon(@Param("tenantId") Long tenantId);

    /**
     * 查询保险已过期的车辆
     * 
     * @param tenantId 租户ID
     * @return 车辆列表
     */
    @Select("SELECT * FROM vehicle WHERE insurance_expiry IS NOT NULL AND " +
            "STR_TO_DATE(insurance_expiry, '%Y-%m-%d') < CURDATE() " +
            "AND tenant_id = #{tenantId} AND deleted = 0 ORDER BY insurance_expiry ASC")
    List<Vehicle> selectInsuranceExpired(@Param("tenantId") Long tenantId);
}